import 'package:dify_api/entities/conversation.dart';
import 'package:flutter/material.dart';
import 'package:fstudy/src/presentation/providers/dify.dart';
import 'package:provider/provider.dart';

// 会话元素
class ConversationItem extends StatelessWidget {
  // 会话信息
  final Conversation conversation;
  final bool selected;

  const ConversationItem({
    super.key,
    required this.conversation,
    required this.selected,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: selected ? Color.fromRGBO(21, 94, 239, 1) : null,
      child: Row(
        children: [
          Icon(Icons.chat),
          Text(conversation.name, overflow: TextOverflow.ellipsis, maxLines: 1),
        ],
      ),
    );
  }
}

// 会话列表
class ConversationList extends StatelessWidget {
  final ScrollController _scrollController = ScrollController();

  ConversationList({super.key});

  @override
  Widget build(BuildContext context) {
    final selected = context.watch<CurrentConversationProvider>();
    final conversation = context.watch<ConversationItemsProvider>();
    final items = conversation.items;

    return SafeArea(
      child: ListView.builder(
        controller: _scrollController,
        padding: EdgeInsets.all(16),
        itemCount: items.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              selected.change(items[index].id);
            },
            child: ConversationItem(
              conversation: items[index],
              selected: items[index].id == selected.id,
            ),
          );
        },
      ),
    );
  }
}
